package xyz.cerberu.cet.subscription.service;

import com.bete.MD5Utils;
import xyz.cerberu.cet.subscription.dao.SubscriptionDao;
import xyz.cerberu.cet.subscription.domain.Subscription;
import xyz.cerberu.cet.subtitle.domain.Subtitle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author β世界
 * Created on 9:00
 * @Description 字幕组订阅服务
 */
@Service
public class SubtitleSubscriptionServerImpl {

    private final SubscriptionDao subscriptionDao;

    @Autowired
    public SubtitleSubscriptionServerImpl(SubscriptionDao subscriptionDao) {
        this.subscriptionDao = subscriptionDao;
    }

    /**
     * @author β世界 on 14:36 2020/6/23
     * 1.封装用户的信息
     * 2.将信息添加到订阅表中
     * @param uid:
     * @param sub:
     **/
    public void add(String uid, int sub) {
        // 封装信息
        String subscriberId = MD5Utils.stringToMD5(uid+sub);
        Subtitle subtitle = new Subtitle();
        subtitle.setSub_id(sub);
        // 存储信息
        subscriptionDao.saveSubscription(uid,subscriberId,sub);
    }

    /**
     * @author β世界 on 15:01 2020/6/23
     * 移除用户的一个订阅信息
     * @param uid : 用户信息
     * @param sub : 订阅ID
     **/
    @Transactional(rollbackFor = {RuntimeException.class})
    public void remove(String uid, int sub) {
        String subscription = MD5Utils.stringToMD5(uid+sub);
        int line = subscriptionDao.deleteSubscription(subscription);
        if(line != 1){
            throw new RuntimeException("删除条目过多");
        }
    }

    /**
     * @author β世界 on 9:37 2021/3/15
     * 检查用户是否订阅
     * @param uid: 用户d的
     * @param sub: 字幕组的id
     * @return boolean
     **/
    public boolean isSubscription(String uid, int sub) {
        return subscriptionDao.findBySubscription(MD5Utils.stringToMD5(uid+sub)) != null;
    }

    /**
     * @author β世界 on 18:11 2020/6/25
     * 查询获取一个用户的所有订阅信息
     * @param uid: 用户的信息
     * @return java.util.List<com.Cet.subscription.domain.Subscription>
     **/
    public List<Subscription> getSubscriptionInfo(String uid) {
        return subscriptionDao.findByUID(uid);
    }

}
